package mylab.io.core.codec;

import com.google.common.base.Preconditions;

import java.net.InetSocketAddress;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import mylab.io.base.model.Msg;


@ChannelHandler.Sharable
public class SimpleDecoder<M extends Msg> extends MessageToMessageDecoder<ByteBuf> {
    public static final String HANDLER_NAME = SimpleDecoder.class.getSimpleName();

    protected MsgResolver<M, ByteBuf> msgResolver;

    public SimpleDecoder(MsgResolver<M, ByteBuf> msgResolver) {
        Preconditions.checkNotNull(msgResolver);
        this.msgResolver = msgResolver;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        List<M> msgList = msgResolver.up(ctx, buf);

        //设置msg收发端
        if (ctx.channel().remoteAddress() instanceof InetSocketAddress remote
                && ctx.channel().localAddress() instanceof InetSocketAddress local) {
            msgList.forEach(msg -> {
                msg.setTerminal(remote, local);
            });
        }

        if (msgList != null && !msgList.isEmpty()) {
            out.addAll(msgList);
        }
    }
}
